package com.wxm.common.file.core.service.supplier;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.wxm.common.file.core.exception.FileException;
import com.wxm.common.file.core.property.QiniuKodoProperty;
import com.wxm.common.file.core.property.UploadBaseProperty;
import org.springframework.util.ObjectUtils;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * <p>
 *      供应商[七牛Kodo文件储存]Service
 * </p>
 *
 * @author: wxm
 * @Date: 2022/1/17
 */
public class QiniuKodoService implements SupplierBaseService {
    private QiniuKodoProperty property;
    private UploadManager uploadManager;
    private BucketManager bucketManager;
    private String token;

    /**
     * 初始化服务端
     */
    private void init(){
        Region r = null;
        if ("huadong".equals(property.getRegion())){//华东
            r = Region.huadong();
        }else if ("huabei".equals(property.getRegion())){//华北
            r = Region.huabei();
        }else if ("huanan".equals(property.getRegion())){//华南
            r = Region.huanan();
        }else if ("beimei".equals(property.getRegion())){//北美
            r = Region.beimei();
        }else if ("xinjiapo".equals(property.getRegion())){//新加坡
            r = Region.xinjiapo();
        }else if("dongnanya".equals(property.getRegion())){//东南亚
            r = Region.regionAs0();
        }else if("huadong-zhejiang2".equals(property.getRegion())){//华东—浙江2
            r = new Region.Builder()
                    .region("cn-east-2")//区域 Region ID
                    .srcUpHost("up-cn-east-2.qiniup.com")//源站上传
                    .accUpHost("upload-cn-east-2.qiniup.com")//加速上传
                    .iovipHost("iovip-cn-east-2.qiniuio.com")//源站下载
                    .rsHost("rs-cn-east-2.qiniuapi.com")//对象管理
                    .rsfHost("rsf-cn-east-2.qiniuapi.com")//对象列举
                    .apiHost("api.qiniu.com")//计量查询
                    .build();
        }else {
            r = Region.autoRegion(); //根据AccessKey和Bucket来判断机房
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(r);
        Auth auth = Auth.create(this.property.getAccessKey(), this.property.getSecretKey());
        this.uploadManager = new UploadManager(cfg);
        this.bucketManager = new BucketManager(auth, cfg);
        this.token =  auth.uploadToken(this.property.getBucket());
    }

    /**
     * 参数非空校验
     */
    private void checkProperty(){
        FileException.isNull(this.property.getAccessKey(),"AccessKey不能为null");
        FileException.isNull(this.property.getSecretKey(),"SecretKey不能为null");
        FileException.isNull(this.property.getBucket(),"Bucket不能为null");
        FileException.isNull(this.property.getDomainOfBucket(),"DomainOfBucket不能为null");
        FileException.isNull(this.property.getRootPath(),"RootPath不能为null");
    }

    @Override
    public void init(UploadBaseProperty uploadBaseProperty) {
        this.property = (QiniuKodoProperty) uploadBaseProperty;
        this.checkProperty();
        this.init();
    }

//    @Override
//    public void uploading(String filePath) throws Exception{
//        this.uploadManager.put(filePath, "", this.token);
//    }
//
//    @Override
//    public void uploading(byte[] uploadBytes, String name) throws Exception{
//        this.uploadManager.put(uploadBytes, name, this.token);
//    }
//
//    @Override
//    public void uploading(File file) throws Exception{
//        this.uploadManager.put(file, file.getName(), this.token);
//    }

    @Override
    public void uploading(InputStream inputStream,String fileName) throws Exception {
        this.uploadManager.put(inputStream,fileName,this.token,new StringMap(),null);
    }

    @Override
    public void delete(String filePath) throws Exception{
        //七牛需要去掉前缀
        String deletePath = this.removeFilePathPrefix(filePath, this.property.getRootPath());
        this.bucketManager.delete(this.property.getBucket(),deletePath);
    }

    /**
     * 对空间内文件访问链接
     * @param fileName 文件名称
     * @return 文件访问url
     */
    private String download(QiniuKodoProperty property,String fileName){
        if ("public".equals(property.getAccessType())){
            return publicDownload(property,fileName);
        }else if ("private".equals(property.getAccessType())){
            return privateDownload(property,fileName);
        }else {
            throw new RuntimeException("七牛云[Kodo]空间权限异常");
        }
    }

    /**
     * 公共空间文件访问
     * @param fileName 文件名称
     * @return 文件访问url
     */
    private String publicDownload(QiniuKodoProperty property,String fileName){
        return String.format("%s/%s", property.getDomainOfBucket(), fileName);
    }

    /**
     * 私有空间文件访问
     * @param fileName 文件名称
     * @return 文件访问url
     */
    public String privateDownload(QiniuKodoProperty property,String fileName){
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String publicUrl = String.format("%s/%s", property.getDomainOfBucket(), encodedFileName);
        Auth auth = Auth.create(property.getAccessKey(), property.getSecretKey());
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        return auth.privateDownloadUrl(publicUrl, expireInSeconds);
    }
}
